package com.beiding.workordersystem.system.service.impl;

import com.beiding.workordersystem.common.service.BaseService;
import com.beiding.workordersystem.common.standard.E;
import com.beiding.workordersystem.common.utils.FileUtils;
import com.beiding.workordersystem.common.utils.QueryUtils;
import com.beiding.workordersystem.common.utils.ResourceUtils;
import com.beiding.workordersystem.system.dao.FileDao;
import com.beiding.workordersystem.system.entity.FileEntity;
import com.beiding.workordersystem.system.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
public class FileServiceImpl extends BaseService implements FileService {

    @Autowired
    private FileDao fileDao;

    @Autowired
    private FileUtils fileUtils;

    @Override
    @Transactional
    public void save(FileEntity serverFile, InputStream inputStream) {
        fillId(serverFile);
        int upload = fileUtils.write(serverFile.getId(), inputStream);
        if (upload == 0) {
            serverFile.setUploadTime(new Date());
            fileDao.insert(serverFile);
        } else {
            switch (upload) {
                case 1:
                    E.error("同名文件已经存在");
                case 2:
                    E.error("目标文件创建失败");
                case 3:
                    E.error("文件保存失败");
            }
        }
    }

    @Override
    public void download(String id) {
        InputStream inputStream = fileUtils.getInputStream(id);
        FileEntity fileEntity = fileDao.selectById(id);
        if (fileEntity != null && inputStream != null) {
            try {
                ResourceUtils.download(inputStream, fileEntity.getName());
                inputStream.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void delete(String id) {
        FileEntity fileEntity = fileDao.selectById(id);
        E.notNull(fileEntity, "文件不存在");

        int delete = fileUtils.delete(id);
        if (delete == 1) {
            E.error("文件不存在");
        } else if (delete == 2) {
            E.error("删除失败");
        }
        fileDao.deleteById(id);
    }

    @Override
    public List<String> listFileByHolderId(String id) {
        return fileDao.getAllIdsByHolderId(id);
    }

    @Override
    @Transactional
    public void claim(String holderId, List<String> fileIds) {
        Date date = new Date();
        for (String id : fileIds) {
            fileDao.claim(holderId, id, date);
        }
    }

}
